package com.nd.android.u.ui.widge;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.StarAppCIConst;
import com.common.allCommon.CommUtil;
import com.common.allCommon.CommonUtils;
import com.common.android.utils.smiley.Smiley;
import com.common.android.utils.smiley.Smileyhelper;
import com.common.commonInterface.IEventMessageProvider;
import com.common.otherInterface.bean.IUserInfo;
import com.common.utils.StarAppUtils;
import com.common.widget.GlobalToast;
import com.nd.android.u.controller.ChatConst.KEY;
import com.nd.android.u.controller.ChatGlobalVariable;
import com.nd.android.u.controller.MessageConst.GroupType;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.message_chat.ChatActivity_Group;
import com.nd.android.u.ui.beanStarApp.DisplayMessage_App;
import com.product.android.commonInterface.BaseCommonStruct;
import com.product.android.commonInterface.CIConst;
import com.product.android.commonInterface.CommonInterfaceManager;
import com.product.android.commonInterface.chat.ChatGroup;

import de.greenrobot.event.EventBus;

/**
 * 应用消息列表控件（除了定制的应用消息之外，其它的应用消息控件都用这个）
 * <br>Created 2014-7-26 下午9:07:45
 * @version  
 * @author   cb		
 * @see 	 
 */
public class ChatListItemView_App extends  LinearLayout implements IChatListItem{
	/** 群数据KEY */
	public static String KEY_GROUP_DATA = "key_group_data";
	private Context mContext;
	private TextView contentText;
	private ImageView logoImg;
	private ImageView msgimg;
	private TextView timeText;
	private LinearLayout  mtextcontextlv;
	private LinearLayout llDetail;
	private DisplayMessage_App mAppMessage;
	/** 消息类型：用户加入群 */
	private static String MESSAGE_TYPE_ADD_GROUP = "groupadd";
	/** 消息类型：群成员变更 */
	private static String MESSAGE_TYPE_GROUP_MEMBER_CHANGE_JOIN = "join";
	/** 消息类型：群成员变更 */
	private boolean mIsLoading=false;
	/***
	 * 线程通讯
	 */
	private Handler mHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg==null){
				return;
			}
			mIsLoading=false;
			final int result=msg.what;
			Log.e("jump","跳转结果为"+result);
			switch (result) {
			case CIConst.COM_RET_NO_NETWORK:
				GlobalToast.showToast(
						R.string.star_app_socket_error, 0);
				break;
			case  CIConst.COM_RET_ERROR:
				GlobalToast.showToast(
						R.string.str_group_chat_not_exist, 0);
				break;
			case CIConst.COM_RET_OK:
				Intent intent = new Intent(mContext, ChatActivity_Group.class);
				Bundle bundle = new Bundle();
				bundle.putString(KEY.GID, mAppMessage.groupId);
				bundle.putInt(KEY.GROUPTYPE, mAppMessage.groupType);
				bundle.putString(KEY.NAME,
						((IEventMessageProvider) mAppMessage)
								.getMessageResult().getStringExtraData());
				((IEventMessageProvider) mAppMessage).getMessageResult();
				intent.putExtras(bundle);
				if (mContext != null) {
					mContext.startActivity(intent);
				}
				break;
			default:
				break;
			}
		};
	};
	
	/**
	 * Creates a new instance of ChatListItemView_App.
	 * <br>Created 2014-7-26 下午9:09:17
	 * @param context
	 */
	public ChatListItemView_App(Context context) {
		super(context);
		this.mContext = context;
		getView();
		initEvent();
	}
	
	/**
	 * 初始化点击事件
	 * <br>Created 2014-11-21 下午5:48:00
	 * @author       ChuXY	
	*/
	private void initEvent() {
		EventBus.getDefault().register(this,BaseCommonStruct.class);
		this.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mContext == null || mAppMessage == null) {
					return;
				}
				if (mAppMessage.object != null
						&& mAppMessage.object instanceof String) {// 系统消息（群，朋友，个人）
					String type = (String) mAppMessage.object;
					if (type.equals(MESSAGE_TYPE_ADD_GROUP)
							|| type.equals(MESSAGE_TYPE_GROUP_MEMBER_CHANGE_JOIN)) {// 群成员变更消息或加入群消息，跳转到指定群聊
						if (Long.valueOf(mAppMessage.groupId) > 0
								&& mAppMessage.groupType == ChatGroup.getNormalGroupType()) {
							if(mIsLoading){
								GlobalToast.showToast(
										R.string.str_group_is_loading, 0);
								return;
							}
							new Thread(new Runnable() {
								@Override
								public void run() {
									mIsLoading=true;
									BaseCommonStruct struct = new BaseCommonStruct();
									struct.lPara = Long
											.valueOf(mAppMessage.groupId);
									struct.obj1 = mContext;
									int ret = CommonInterfaceManager.INSTANCE
											.CommonInterfaceID(
													CIConst.MAIN_MODELID,
													StarAppCIConst.CHAT_NOTIFY_GROUP_EXIST_210006,
													struct);
									mHandler.sendEmptyMessage(ret);
								}
							}) {

							}.start();
						}
					}// FRI CXY 其他IM消息跳转，待加
				}
			}
		});
	}

	
	/**
	 * 初始化控件
	 * <br>Created 2014-7-26 下午9:10:37
	 * @author       cb
	*/
	private void getView(){
		LayoutInflater.from(mContext).inflate(R.layout.todo_message_item, this, true);
		contentText = (TextView) this.findViewById(R.id.todo_message_item_content);
		contentText.setTextSize(ChatGlobalVariable.getInstance().getChatTextSize());
		logoImg = (ImageView) this.findViewById(R.id.todo_message_item_face);
		msgimg=(ImageView)this.findViewById(R.id.todo_message_item_img);
		timeText = (TextView)this.findViewById(R.id.todo_message_item_tv);
		timeText.setTextSize(ChatGlobalVariable.getInstance().getChatTimeTextSize());
		mtextcontextlv = (LinearLayout)this.findViewById(R.id.textcontextlv);
		llDetail=(LinearLayout)findViewById(R.id.llDetail);
		TextView tvDetail=(TextView) this.findViewById(R.id.tvDetail);
		
		StarAppUtils.setViewTypeFace(contentText, false);
		StarAppUtils.setViewTypeFace(timeText, false);
		StarAppUtils.setViewTypeFace(tvDetail, false);
	}
	
	/**
	 * 设置数据
	 * <br>Created 2014-7-26 下午9:24:08
	 * @param message
	 * @author       cb
	*/
	public void setData(IMessageDisplay message) {
		llDetail.setVisibility(View.GONE);
		mAppMessage=(DisplayMessage_App) message;
		String msgtxt=mAppMessage.displayContent;
		if (mAppMessage.oriMessage.contains("@picture")){
			//暗恋消息里如果带有"@picture"字符串的话，要把图片显示出来
			msgimg.setVisibility(View.VISIBLE);
		}else{
			msgimg.setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(mAppMessage.url)){
			llDetail.setVisibility(View.VISIBLE);
		}
		if(CommonUtils.isHtml(msgtxt)){           //如果是网页
			contentText.setText(Smileyhelper.getInstance().getHtml(msgtxt));
			contentText.setMovementMethod(LinkMovementMethod.getInstance());
			contentText.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							mtextcontextlv.setPressed(true);
							break;
						case MotionEvent.ACTION_CANCEL:
						case MotionEvent.ACTION_UP:
							mtextcontextlv.setPressed(false);
					}
					return false;
				}
			});
			contentText.setFocusable(true);
		}else{
			if(!TextUtils.isEmpty(msgtxt)){
				contentText.setText(Smileyhelper.getInstance().getSmileySpannableString(msgtxt,
	                    Smiley.TYPE_CHAT, Smiley.SIZE_TEXT));
			}
		}
		timeText.setVisibility(View.VISIBLE);
		timeText.setText(message.getTimeString());
		message.displayPortrait(logoImg, false);
	}

	@Override
	public IMessageDisplay getData() {
		return mAppMessage;
	}
	
	/**
	 * EventBus接收函数,更新头像
	 * 
	 * <br>
	 * Created 2014-10-29 下午4:07:30
	 * 
	 * @param struct
	 *            传递的数据
	 * @author : ChuXY
	 */
	public void onEventMainThread(BaseCommonStruct struct) {
		CommUtil.updateSculptureImageShown(struct, logoImg);
	}
}